package com.yurun.controller;

import com.yurun.entity.User;
import com.yurun.model.dto.LoginInfo;
import com.yurun.model.vo.Result;
import com.yurun.service.UserService;
import com.yurun.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 后台登陆页面
 */
@RestController
public class LoginController {
    @Autowired
    UserService userService;
    /**
     * @Description: 登录表单
     * @Param: loginInfo
     * @return: com.yurun.model.vo.Result
     * @Author: JimmyYao
     * @Date: 2022/2/9
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginInfo loginInfo){
        User user=userService.findByUsernameAndPassword(loginInfo.getUsername(),loginInfo.getPassword());

        if(!"ROLE_admin".equals(user.getRole())){
            return Result.create(403,"无权限");
        }
        user.setPassword(null);

        String jwt= JwtUtils.generateToken("admin:"+user.getUsername());
        Map<String,Object> map=new HashMap<>();
        map.put("user",user);
        map.put("token",jwt);

        return Result.ok("登陆成功",map);
    }
}
